/**
 * @name Login
 * @author darcrand
 * @desc 登录页面
 */

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import { Button, Form, Input } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { apiGetBingWallpaper } from '@/apis/common'

import logoColor from '@/assets/images/afaire-logo-color-128.png'
import styles from './styles.module.less'

@inject('user')
@observer
class Login extends Component {
  state = { bannerUrl: '' }
  refForm = React.createRef()

  componentDidMount() {
    apiGetBingWallpaper().then(url => this.setState({ bannerUrl: url }))
  }

  onFormFinish = async (values = {}) => {
    try {
      await this.props.user.login(values)
      this.props.history.replace('/')
    } catch (err) {
      console.error('登录失败', err)
    }
  }

  render() {
    const { bannerUrl } = this.state
    return (
      <div className={styles.container}>
        <div className={styles.banner} style={{ backgroundImage: `url("${bannerUrl}")` }}></div>

        <div className={styles.form_container}>
          <main className={styles.content}>
            <img src={logoColor} alt='afaire' className={styles.logo_color} />
            <h2 className={styles.title}>Login</h2>
            <Form ref={this.refForm} onFinish={this.onFormFinish}>
              <Form.Item name='username' rules={[{ required: true, message: 'Please input your username!' }]}>
                <Input size='large' prefix={<UserOutlined />} placeholder='email' />
              </Form.Item>
              <Form.Item name='password' rules={[{ required: true, message: 'Please input your password!' }]}>
                <Input.Password size='large' prefix={<LockOutlined />} placeholder='password' />
              </Form.Item>

              <Form.Item>
                <Button type='primary' htmlType='submit' block size='large' className={styles.submit_btn}>
                  login
                </Button>
              </Form.Item>
            </Form>
            <p className={styles.sign_up_row}>
              <span>Don't have an account?</span>
              <Link to='/sign-up'>Join Us</Link>
            </p>
          </main>
        </div>
      </div>
    )
  }
}

export default Login
